package dealfinder

class Coupon {
    
    Deal deal
    User user
    String code

    static constraints = {
    }
    
    /*
     *Method for creating all coupons for a specific deal.
     */
    static Boolean generateAllCoupons(Deal deal){
        for(User user in deal.users){
            if(!this.generateSingleCoupon(deal, user)){
                return false
            }
        }
    }
    
    /**
     *Method for generating coupon to the specified user,
     *its creating the coupon code. 
     *
    */
    static Boolean generateSingleCoupon(Deal deal, User user){
        String stringHolder = user.firstName.substring(0,1)
        stringHolder = stringHolder + user.lastName.substring(0,1)
        String phoneString = user.phoneNumber.toString()
        stringHolder = stringHolder + phoneString.substring(0,2)
        stringHolder = stringHolder + deal.name.substring(0,2)
        Coupon coupon = new Coupon(deal: deal, user: user, code: stringHolder).save(flush:true)
        return true
    }
}
